package cn.glutnn.service.impl;

import cn.glutnn.entity.Order;
import cn.glutnn.entity.Result;
import cn.glutnn.entity.vo.ShoppingcartVo;
import cn.glutnn.mapper.ShoppingcartMapper;
import cn.glutnn.service.OrderService;
import cn.glutnn.service.ShoppingcartService;
import cn.glutnn.utils.ThreadLocalUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.glutnn.entity.Shoppingcart;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * (Shoppingcart)表服务实现类
 *
 * @author msh
 * @since 2024-10-25 09:49:32
 */
@Service
public class ShoppingcartServiceImpl extends ServiceImpl<ShoppingcartMapper, Shoppingcart> implements ShoppingcartService {

    @Autowired
    private OrderService orderService;

    @Override
    public void add(Integer id) {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        Shoppingcart shoppingcart = new Shoppingcart(null, id, 1, username, new Date(), new Date());
        LambdaQueryWrapper<Shoppingcart> wrapper = new LambdaQueryWrapper<Shoppingcart>();
        wrapper.eq(Shoppingcart::getOrderId, id);
        List<Shoppingcart> shoppingcarts = list(wrapper);
        if (shoppingcarts.size() == 0) {
            save(shoppingcart);
        } else {
            Shoppingcart shoppingcart1 = shoppingcarts.get(0);
            Integer count = shoppingcart1.getCount() + 1;
            shoppingcart1.setCount(count);
            updateById(shoppingcart1);
        }
    }

    @Override
    public Result<List<ShoppingcartVo>> selectAllByOwnName() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        LambdaQueryWrapper<Shoppingcart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Shoppingcart::getOwnName, username);
        List<Shoppingcart> shoppingcarts = list(wrapper);
        ArrayList<ShoppingcartVo> cartsVo = new ArrayList<>();
        for (Shoppingcart shoppingcart : shoppingcarts) {
            ShoppingcartVo shoppingcartVo = new ShoppingcartVo();
            BeanUtils.copyProperties(shoppingcart, shoppingcartVo);
            shoppingcartVo.setOrder(orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderId, shoppingcart.getOrderId())));
            cartsVo.add(shoppingcartVo);
        }
        return Result.success(cartsVo);
    }
}

